using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.IO;
using System.Xml.Serialization;
using System.Threading;
using Ltf.Remoting.TeamFoundation;
using Ltf.Remoting.RemoteEvents;
using Ltf.Remoting.Server;
using Ltf.Remoting.Operations;

using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;


// conflict comments go here
namespace Ltf.Remoting.Commands
{
	public class OverlayScanningEventArgs : EventArgs
	{
		public string FileName;
		public bool Cancel = false;
		public bool Skip = false;
		public OverlayScanningEventArgs(string fileName)
		{
			FileName = fileName;
		}

	}

	public class GenerateOverlayInfo : TFVCClientCommandBase
	{
		[System.Runtime.InteropServices.DllImport("imagehlp.dll")]
		public static extern int MapFileAndCheckSumA(string fileName, ref int headerSum, ref int checkSum);

		public event EventHandler FileStatusScan;

		private string folderPath;
		private bool recurse;

		private string userName;

		private static List<string> foldersInProcess;


		static GenerateOverlayInfo()
		{
			foldersInProcess = new List<string>();
		}

		public GenerateOverlayInfo(TFServerConnection connection)
			: this(connection, string.Empty, false)
		{ }


		public GenerateOverlayInfo(TFServerConnection connection, string folderPath)
			: this(connection, folderPath, false)
		{ }


		public GenerateOverlayInfo(TFServerConnection connection, string folderPath, bool recurse)
			: base(connection)
		{
			this.folderPath = folderPath;
			this.recurse = recurse;
			userName = connection.Settings.GetTFSUserName();
		}

		public void TestFolder()
		{
			TestFolder(folderPath);
		}

		private static ExtendedItem[] lastExtendedItems =new ExtendedItem[0];
		private static DateTime lastExtendedItemsTime = new DateTime(1900, 1, 1);
		private static string lastExtendedItemsFolderPath = string.Empty;

		public int TestFolder(string folderPath)
		{
			if (foldersInProcess.Contains(folderPath))
				return 0;
			if (!Directory.Exists(folderPath))
				return 0;

			Monitor.Enter(foldersInProcess);
			foldersInProcess.Add(folderPath);
			int folderLevel = (int)LizardOverLayStatus.ReadOnly;
			try
			{
				Workspace ws = Connection.GetWorkspace(folderPath);
				WorkingFolder wf = null;
				ExtendedItem[] eItems = new ExtendedItem[0];
				Dictionary<string, ExtendedItem> extItemsByLocalName = new Dictionary<string, ExtendedItem>();
				if (ws != null)
				{
					wf = ws.GetWorkingFolderForLocalItem(folderPath);
					if (lastExtendedItemsFolderPath != folderPath
						|| lastExtendedItemsTime < DateTime.Now.Subtract(new TimeSpan(0,0,2)))
					{
						ItemSpec ispec = new ItemSpec(wf.ServerItem, RecursionType.OneLevel);
						Console.WriteLine("Getting extended items for "+folderPath);
						eItems = ws.GetExtendedItems(new ItemSpec[] { ispec }, DeletedState.NonDeleted, ItemType.Any)[0];
						lastExtendedItems = eItems;
						lastExtendedItemsFolderPath = folderPath;
						lastExtendedItemsTime = DateTime.Now;
					}
					else
					{
						eItems = lastExtendedItems;
					}
					foreach (ExtendedItem ei in eItems)
						if (ei.LocalItem != null && ei.LocalItem != string.Empty)
							extItemsByLocalName.Add(ei.LocalItem, ei);
				}

				string ltfvcPath = base.Connection.GetMetaFolder(folderPath, true);
				Dictionary<string, LizardFileInfo> fileInfos = new Dictionary<string, LizardFileInfo>();
				int fileCount = 0, fileInfoCount = 0, fileNotChangedCount = 0;

				List<string> foundFiles = new List<string>();

				foreach (string filePath in Directory.GetFiles(folderPath))
				{
					string fileName = Path.GetFileName(filePath);
					string ltfvcFile = Path.Combine(ltfvcPath, fileName + ".ltfvc");
					if (File.Exists(ltfvcFile))
					{
						LizardFileInfo fileInfo = ServerFunctions.GetFileInfoFromFile(ltfvcFile);
						
						fileInfos.Add(fileName, fileInfo);
						fileInfoCount++;
						if (extItemsByLocalName.ContainsKey(filePath))
						{
							foundFiles.Add(filePath);
							ExtendedItem extItem = extItemsByLocalName[filePath];
							if (extItem.VersionLatest != fileInfo.ServerVersion)
								break;
							LizardFileInfo extInfo = new LizardFileInfo();
							extInfo.FillFromExtendedItem(extItem);
							extInfo.CalculateOverlayStatus(userName);
							if (fileInfo.OverlayType != extInfo.OverlayType)
								break;

						}
						if (File.GetCreationTime(filePath) == fileInfo.FileCreatedDate
							&& File.GetLastWriteTime(filePath) == fileInfo.FileWrittenDate
							&& (((File.GetAttributes(filePath) & FileAttributes.ReadOnly) != 0) == fileInfo.ReadOnly))
							fileNotChangedCount++;
						else
							break;

					}
					else
						break;
					fileCount++;
				}

				if (fileInfoCount == fileNotChangedCount && fileInfoCount == fileCount && fileCount==extItemsByLocalName.Count)
				{
					Console.WriteLine(string.Format("Processing folder {0} does not need TFS access", folderPath));
					string folderStatus=Path.Combine(ltfvcPath, "ltfvc.folderstatus");
					if (File.Exists(folderStatus))
						return (int)Enum.Parse(typeof(LizardOverLayStatus), File.ReadAllText(folderStatus));

					return 0;
				}
				Console.WriteLine(string.Format("Processing folder {0} needs TFS access", folderPath));

				string ltfvcFolderName = base.Connection.Settings.LtfMetaFolderName;

				if (ws != null)
				{
					ItemSet items = ws.VersionControlServer.GetItems(wf.ServerItem, RecursionType.OneLevel);
					Dictionary<string, Item> itemDict = new Dictionary<string, Item>();
					foreach (Item i in items.Items)
						itemDict.Add(i.ServerItem, i);
					foreach (ExtendedItem ei in eItems)
					{

						if (itemDict.ContainsKey(ei.SourceServerItem))
						{
							Item item = itemDict[ei.SourceServerItem];
							int fl = GenerateFileStatus(folderLevel, ei, item, false, fileInfos, false, ws);
							if (fl > folderLevel)
								folderLevel = fl;
						}
						else
						{
							string ltfvcFile = Path.Combine(ltfvcPath, Path.GetFileName(ei.LocalItem) + ".ltfvc");

							//TODO: check if Add is pending!
							PendingChange[] pcs = ws.GetPendingChanges(ei.LocalItem);
							if (pcs.Length > 0)
							{
								LizardFileInfo fileInfo = new LizardFileInfo();

								DateTime writtenDate = new DateTime(1900, 1, 1);
								DateTime createdDate = new DateTime(1900, 1, 1);
								if (File.Exists(ei.LocalItem))
								{
									writtenDate = File.GetLastWriteTime(ei.LocalItem);
									createdDate = File.GetCreationTime(ei.LocalItem);
									fileInfo.ReadOnly = (File.GetAttributes(ei.LocalItem) & FileAttributes.ReadOnly) != 0;
								}
								fileInfo.FileCreatedDate = createdDate;
								fileInfo.FileWrittenDate = writtenDate;


								WriteLtfvcFile(fileInfo, LizardFileStatus.Added, ei, ltfvcFile, false);
								folderLevel = (int)LizardOverLayStatus.Add;
							}
						}
					}
					foreach (string subfolder in Directory.GetDirectories(folderPath))
					{
						string subLtfFolder = base.Connection.GetMetaFolder(subfolder);
						if (Directory.Exists(subLtfFolder))
						{
							DateTime dirlw = Directory.GetLastWriteTimeUtc(subfolder);
							DateTime statuswr = DateTime.Now;
							string subsf = Path.Combine(subLtfFolder, "ltfvc.folderstatus");
							if (File.Exists(subsf))
							{
								string sflTEst = File.ReadAllText(subsf);
								LizardOverLayStatus subStatus = (LizardOverLayStatus)Enum.Parse(typeof(LizardOverLayStatus), sflTEst);
								if (((int)folderLevel < ((int)subStatus)))
									folderLevel = (int)subStatus;
							}
						}
					}
					string doneFile =   Path.Combine(base.Connection.GetMetaFolder(folderPath, true), "ltfvc.folderstatus");

					LizardOverLayStatus folt = (LizardOverLayStatus)folderLevel;
					if (File.Exists(doneFile))
					{
						File.SetAttributes(doneFile, FileAttributes.Normal);
					}
					File.WriteAllText(doneFile, folt.ToString());
				}
			}
			catch (Exception e)
			{
				return folderLevel;
			}
			finally
			{
				foldersInProcess.Remove(folderPath);
				Monitor.Exit(foldersInProcess);
			}
			return folderLevel;
		}

		public void GenerateFileStatuses(ExtendedItem[][] extItems, Workspace workspace)
		{
			GenerateFileStatuses(extItems, false, workspace);
		}

		public void GenerateFileStatuses(ExtendedItem[][] extItems, bool isForced, Workspace workspace)
		{
			Dictionary<string, LizardOverLayStatus> folderStatuses = new Dictionary<string, LizardOverLayStatus>();
			bool cancel = false;
			foreach (ExtendedItem[] extItemArray in extItems)
			{
				foreach (ExtendedItem extItem in extItemArray)
				{
					ProgressIndicatorEventArgs piArgs = new ProgressIndicatorEventArgs(extItem.SourceServerItem);
					if (FileStatusScan != null)
						FileStatusScan(this, piArgs);
					cancel = piArgs.Cancel;
					if (cancel)
						break;
					if (!piArgs.Skip)
					{
						if (extItem.LocalItem != null && extItem.LocalItem != string.Empty)
						{
							string localPath = Path.GetDirectoryName(extItem.LocalItem);

							string folderPath = Connection.GetMetaFolder(localPath);

							if (Connection.Settings.IsFolderPathIncluded(localPath))
							{
								if (!Directory.Exists(folderPath))
								{
									Lizardenator lz = new Lizardenator();
									lz.AddLizardFolder(localPath, false);
								}
								string folderStatusFile = Path.Combine(folderPath, "ltfvc.folderstatus");

								LizardOverLayStatus folderStatus = LizardOverLayStatus.None;
								if (folderStatuses.ContainsKey(folderStatusFile))
								{
									folderStatus = folderStatuses[folderStatusFile];
								}
								if (extItem.ItemType == ItemType.File)
								{
									int folderLevel = GenerateFileStatus(0, extItem, null, false, null, isForced, workspace);
									if (folderLevel >= (int)folderStatus)
										folderStatuses[folderStatusFile] = (LizardOverLayStatus)folderLevel;
								}
							}
						}
					}
				}
				if (cancel)
					break;
			}
			// Sort the folders desc, so enumerations will start with leafs
			string[] keyArray = new string[folderStatuses.Count];
			folderStatuses.Keys.CopyTo(keyArray, 0);
			List<string> keyList = new List<string>(keyArray);
			keyList.Sort();
			keyList.Reverse();

			foreach (string key in keyList)
			{
				LizardOverLayStatus status = folderStatuses[key];
				string folderName = Path.GetDirectoryName(Path.GetDirectoryName(key));
				foreach (string childFolder in Directory.GetDirectories(folderName))
				{
					string childFolderStatusFile = Path.Combine(base.Connection.GetMetaFolder(childFolder), "ltfvc.folderstatus");
					if (File.Exists(childFolderStatusFile))
					{
						string childFolderStatusText = File.ReadAllText(childFolderStatusFile);
						LizardOverLayStatus childStatus = (LizardOverLayStatus)Enum.Parse(typeof(LizardOverLayStatus), childFolderStatusText);
						if (((int)childStatus) > ((int)status))
							status = childStatus;

					}

				}
				File.WriteAllText(key, status.ToString());


			}
			ProgressIndicatorEventArgs finishArgs = new ProgressIndicatorEventArgs("Completed");
			if (FileStatusScan != null)
				finishArgs.Finished = true;
			FileStatusScan(this, finishArgs);
		}

		public void GenerateFileStatus(ExtendedItem extItem, bool getOtherPends, Workspace workspace)
		{
			GenerateFileStatus(0, extItem, null, getOtherPends, null, false, workspace);
		}

		public void GenerateFileStatus(ExtendedItem extItem, Item item, bool getOtherPends, Workspace workspace)
		{
			GenerateFileStatus(0, extItem, item, getOtherPends, null, false, workspace);
		}

		internal int GenerateFileStatus(int folderLevel, ExtendedItem extItem, 
			Item item, bool getOtherPends, Dictionary<string, LizardFileInfo> fileInfos,
			bool isForced, Workspace workspace)
		{
			// normally we'll be passed the extendeditem, but if not we will load it here
			if (extItem == null)
			{
				ItemSpec[] itemSpecs = new ItemSpec[] { new ItemSpec(item.ServerItem, RecursionType.None) };
				ExtendedItem[] eiArray = workspace.GetExtendedItems(itemSpecs, DeletedState.NonDeleted, ItemType.Any)[0];
				extItem = eiArray[0];
			}
			bool isDiff = false;

			bool isPendingDelete = ((extItem.ChangeType & ChangeType.Delete) == ChangeType.Delete);

			//first track down the meta-data file, if there is one
			string folderPath = Path.GetDirectoryName(extItem.LocalItem);
			string fileName = Path.GetFileName(extItem.LocalItem);
			if (fileName == null && !isPendingDelete)
				return folderLevel;
			string ltfvcPath = null;
			string ltfvcFile =null;

			if (isPendingDelete)
			{
				string parentFolderServerName = Path.GetDirectoryName(item.ServerItem).Replace('\\','/');
				ItemSpec[] itemSpecs = new ItemSpec[] { new ItemSpec(parentFolderServerName, RecursionType.None)};
				ExtendedItem pExtItem = workspace.GetExtendedItems(itemSpecs, DeletedState.NonDeleted, ItemType.Any)[0][0];
				ltfvcPath = base.Connection.GetMetaFolder(pExtItem.LocalItem);
				ltfvcFile = Path.Combine(ltfvcPath, Path.GetFileName(item.ServerItem) + ".ltfvc");
			
			}
			else
			{
				ltfvcPath = base.Connection.GetMetaFolder(folderPath);
				ltfvcFile = Path.Combine(ltfvcPath, fileName + ".ltfvc");
			}

			LizardFileInfo fileInfo;
			if (fileInfos != null && fileInfos.ContainsKey(ltfvcFile))
				fileInfo = fileInfos[ltfvcFile];
			else if (File.Exists(ltfvcFile))
				fileInfo = ServerFunctions.GetFileInfoFromFile(ltfvcFile);
			else
				fileInfo = new LizardFileInfo();

			//find out about the file...
			DateTime writtenDate = new DateTime(1900, 1, 1);
			DateTime createdDate = new DateTime(1900, 1, 1);
			bool readonlyFlag = false;
			if (File.Exists(extItem.LocalItem))
			{
				writtenDate = File.GetLastWriteTime(extItem.LocalItem);
				createdDate = File.GetCreationTime(extItem.LocalItem);
				readonlyFlag = (File.GetAttributes(extItem.LocalItem) & FileAttributes.ReadOnly) != 0;
			}

			LizardFileInfo extInfo = new LizardFileInfo();
			extInfo.FillFromExtendedItem(extItem);
			extInfo.CalculateOverlayStatus(userName);

			// check for changes in write protection, created/written dates, versions, or overlay statuses
			if (fileInfo.ReadOnly != readonlyFlag 
				|| fileInfo.FileCreatedDate != createdDate 
				|| fileInfo.FileWrittenDate != writtenDate
				|| fileInfo.ServerVersion != extItem.VersionLatest
				|| fileInfo.OverlayType !=extInfo.OverlayType
				|| isForced)
			{
				fileInfo.FileCreatedDate = createdDate;
				fileInfo.FileWrittenDate = writtenDate;
				fileInfo.ReadOnly = readonlyFlag;

				LizardFileStatus newStatus = LizardFileStatus.Same;

				if ((extItem.ChangeType & ChangeType.Add) != ChangeType.Add)
				{
					if (File.Exists(extItem.LocalItem) && extItem.DeletionId == 0)
					{
						int hs1 = 0, cs1 = 0;
						int hs2 = 0, cs2 = 0;

						if (extItem.VersionLocal != fileInfo.LocalVersion || fileInfo.LocalVersionLength == 0 || fileInfo.LocalVersionChecksum == 0)
						{
							// if the 'item' was not provided get it now
							if (extItem.VersionLocal != 0 && item == null)
								item = base.Connection.VersionControlServer.GetItem(extItem.ItemId, extItem.VersionLocal);
							if (item != null)
								fileInfo.LocalVersionLength = item.ContentLength;
						}

						// if we've got an item, and a local version we can start comparing
						if (item != null || ( extItem.ItemId != 0 && extItem.VersionLocal != 0))
						{
							if (item == null)
							{
								Workspace ws = Connection.GetWorkspace(extItem.LocalItem);
								Connection.VersionControlServer.GetItem(extItem.ItemId, extItem.VersionLocal);
							}

							if (fileInfo.LocalVersionLength == new FileInfo(extItem.LocalItem).Length)
							{
								// different versions or no local version? Get version from server and get the checksum
								if (extItem.VersionLocal != fileInfo.LocalVersion || fileInfo.LocalVersionLength == 0 || fileInfo.LocalVersionChecksum == 0)
								{
									string ltfvcServerFile = Path.Combine(ltfvcPath, fileName + ".server");
									item.DownloadFile(ltfvcServerFile);
									int fh2 = MapFileAndCheckSumA(ltfvcServerFile, ref hs2, ref cs2);

									fileInfo.LocalVersionChecksum = cs2;
									fileInfo.LocalVersion = extItem.VersionLocal;
								}

								// different dates from last checksum? get a new one.
								if (writtenDate >= fileInfo.WorkspaceVersionChecksumDate || createdDate >= fileInfo.WorkspaceVersionChecksumDate)
								{
									int fh1 = MapFileAndCheckSumA(extItem.LocalItem, ref hs1, ref cs1);
									fileInfo.WorkspaceVersionChecksumDate = DateTime.Now;
									fileInfo.WorkspaceVersionChecksum = cs1;
								}

								isDiff |= (fileInfo.LocalVersionChecksum != fileInfo.WorkspaceVersionChecksum);

							}
							else
							{
								isDiff = true;
							}
						}

					}
					else if ((extItem.ChangeType & ChangeType.Delete) == ChangeType.Delete)
					{
						// it's been deleted in TFS!
						newStatus = LizardFileStatus.Deleted;
					}
					else if (extItem.DeletionId != 0)
					{
						// it's been deleted in TFS and the local copy is actually a new uncontrolled file
						if (File.Exists(ltfvcFile))
							File.Delete(ltfvcFile);
						return (int)LizardOverLayStatus.None;
					}
					else
					{
						// its different in TFS to the local copy 
						isDiff = true;
					}
					if (newStatus != LizardFileStatus.Deleted)
						newStatus = isDiff ? LizardFileStatus.Different : LizardFileStatus.Same;

					WriteLtfvcFile(fileInfo, newStatus, extItem, ltfvcFile, getOtherPends);
				}
				else
				{
					WriteLtfvcFile(fileInfo, LizardFileStatus.Added, extItem, ltfvcFile, getOtherPends);
				}
			}
			else
			{
				isDiff = (fileInfo.Status == LizardFileStatus.Different);
			}
			// work out the folder level...
			if (isDiff)
			{
				if (extItem.VersionLatest != extItem.VersionLocal)
				{
					if (extItem.ChangeType == ChangeType.None)
						folderLevel = (int)LizardOverLayStatus.OutOfDate;
					else
						folderLevel = (int)LizardOverLayStatus.Conflict;
				}
				else
					folderLevel = (int)LizardOverLayStatus.Different;
			}
			else if (folderLevel == (int)LizardOverLayStatus.ReadOnly && extItem.ChangeType != ChangeType.None)
			{
				if (extItem.VersionLatest != extItem.VersionLocal)
					folderLevel = (int)LizardOverLayStatus.OutOfDate;
				else
					folderLevel = (int)LizardOverLayStatus.CheckedOut;
			}
			else
				folderLevel = (int)LizardOverLayStatus.ReadOnly;
			return folderLevel;
		}

		private void WriteLtfvcFile(LizardFileInfo fileInfo, LizardFileStatus status, ExtendedItem extendedItem, string fileName, bool getOtherPends)
		{
			fileInfo.Status = status;
			fileInfo.FillFromExtendedItem(extendedItem);

			if (getOtherPends)
			{
				try
				{
					PendingSet[] pss = base.Connection.VersionControlServer.QueryPendingSets(new string[] { extendedItem.SourceServerItem },RecursionType.None, "", "");
					List<string> otherPends = new List<string>();
					foreach (PendingSet ps in pss)
					{
						if (ps.OwnerName != System.Environment.UserName || ps.Computer != System.Environment.MachineName)
						{
							string pend = string.Format("{0} on {1}", ps.OwnerName, ps.Computer);
							otherPends.Add(pend);
						}
					}
					fileInfo.OtherUsers = string.Join(", ", otherPends.ToArray());
				}
				catch (Exception ex)
				{
					fileInfo.OtherUsers = "Could not get list";
				}
			}
			fileInfo.CalculateOverlayStatus(userName);

			if (File.Exists(fileName))
			{
				File.SetAttributes(fileName, FileAttributes.Normal);
				File.Delete(fileName);
			}
			XmlSerializer xs = new XmlSerializer(typeof(LizardFileInfo));
			using (Stream s = new FileStream(fileName, FileMode.CreateNew))
			{
				xs.Serialize(s, fileInfo);
				s.Flush();
			}

			string binaryFileName = fileName + ".bin";
			BinaryFormatter bf = new BinaryFormatter();
			if (File.Exists(binaryFileName))
			{
				File.SetAttributes(binaryFileName, FileAttributes.Normal);
				File.Delete(binaryFileName);
			}
			using (Stream s = new FileStream(binaryFileName, FileMode.CreateNew))
			{
				bf.Serialize(s, fileInfo);
				s.Flush();
			}
			
		}

		//private LizardOverLayStatus GetOverlayStatus(LizardFileInfo fileInfo)
		//{
		//  LizardOverLayStatus olt = LizardOverLayStatus.None;
		//  if (fileInfo.Status == LizardFileStatus.Same && fileInfo.LockStatus == "None" && fileInfo.ChangeType.IndexOf("Edit") >= 0 && fileInfo.LocalVersion == fileInfo.ServerVersion)
		//    olt = LizardOverLayStatus.CheckedOut;
		//  if (fileInfo.Status == LizardFileStatus.Same && fileInfo.LockStatus == "None" && fileInfo.ChangeType.IndexOf("Edit") >= 0 && fileInfo.LocalVersion != fileInfo.ServerVersion)
		//    olt = LizardOverLayStatus.OutOfDate;
		//  if (fileInfo.Status == LizardFileStatus.Same && fileInfo.LockStatus == "None" && fileInfo.ChangeType == "None" && fileInfo.LocalVersion == fileInfo.ServerVersion)
		//  {
		//    olt = LizardOverLayStatus.ReadOnly;
		//  }
		//  if (fileInfo.Status == LizardFileStatus.Different && fileInfo.LockStatus == "None" && fileInfo.ChangeType.IndexOf("Edit") >= 0 && fileInfo.LocalVersion == fileInfo.ServerVersion)
		//    olt = LizardOverLayStatus.CheckedOut;
		//  if (Path.GetFileName(fileInfo.ServerPath) != Path.GetFileName(fileInfo.LocalItem))
		//    olt = LizardOverLayStatus.Other; // renamed!
		//  if (fileInfo.LockStatus == "None" && fileInfo.ChangeType == "None" && fileInfo.LocalVersion != fileInfo.ServerVersion)
		//    olt = LizardOverLayStatus.OutOfDate;
		//  if (fileInfo.Status == LizardFileStatus.Same && fileInfo.LockStatus != "None")
		//    olt = LizardOverLayStatus.Locked;
		//  if (fileInfo.Status == LizardFileStatus.Different && fileInfo.LocalVersion == fileInfo.ServerVersion)
		//  {
		//    if (fileInfo.ChangeType.ToString() == "None")
		//      olt = LizardOverLayStatus.CheckedInWritable;
		//    else
		//      olt = LizardOverLayStatus.Different;
		//  }
		//  if (fileInfo.Status == LizardFileStatus.Different && fileInfo.ChangeType.IndexOf("Edit") >= 0 && fileInfo.LocalVersion != fileInfo.ServerVersion)
		//    olt = LizardOverLayStatus.Conflict;
		//  if (fileInfo.Status == LizardFileStatus.Added)
		//    olt = LizardOverLayStatus.Add;
		//  if (fileInfo.Status == LizardFileStatus.Deleted)
		//    olt = LizardOverLayStatus.Deleted;
		//  if (fileInfo.ChangeType.IndexOf("Branch") >= 0 || fileInfo.ChangeType.IndexOf("Rename") >= 0)
		//    olt = LizardOverLayStatus.Different;

		//  if (olt == LizardOverLayStatus.Different && (fileInfo.ChangeType.IndexOf("Branch") >= 0))
		//    olt = LizardOverLayStatus.Add;
		//  if (fileInfo.LockStatus == "None" && fileInfo.ChangeType == "None" && fileInfo.LocalVersion == fileInfo.ServerVersion)
		//  {
		//    olt = LizardOverLayStatus.ReadOnly;
		//  }
		//  if ((fileInfo.LockStatus == "None" || fileInfo.LockOwner != userName) && fileInfo.ChangeType == "None" && fileInfo.Status == LizardFileStatus.Different)
		//  {
		//    olt = LizardOverLayStatus.CheckedInWritable;
		//  }
		//  return olt;
		//}

		

		public LizardFileInfo GetFileInfoForPath(string path, bool regenerateInfo)
		{
			if (regenerateInfo)
			{
				Workspace ws = Connection.GetWorkspace(path);
				if (ws!=null)
				{
					ItemSpec[] iss = new ItemSpec[] { new ItemSpec(path,RecursionType.None) };
					ExtendedItem[] extItems = ws.GetExtendedItems(iss, DeletedState.NonDeleted, ItemType.File)[0];
					if (extItems.Length == 1)
					{
						Item item = ws.VersionControlServer.GetItem(path, VersionSpec.Latest);
						GenerateFileStatus(extItems[0], item, true, ws);
					}
				}
			}

			string folderPath = Path.GetDirectoryName(path);
			string fileName = Path.GetFileName(path);
			if (fileName == null)
				return null;
			string ltfvcPath = base.Connection.GetMetaFolder(folderPath);
			string ltfvcFile = Path.Combine(ltfvcPath, fileName + ".ltfvc");
			if (File.Exists(ltfvcFile))
				return ServerFunctions.GetFileInfoFromFile(ltfvcFile);
			else
				return null;
		}

	}
}
